//
//  KLSGLeftSliderViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGLeftSliderViewController.h"

@interface KLSGLeftSliderViewController ()<UIGestureRecognizerDelegate>
{
    CGFloat _scalef;  //实时横向位移
}

@property (nonatomic,strong) UITableView *leftTableview;
@property (nonatomic,assign) CGFloat leftTableviewW;
@property (nonatomic,strong) UIView *contentView;


@end

@implementation KLSGLeftSliderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 添加背景图片
    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgImage.image = [UIImage imageNamed:@"leftBg"];
    [self.view addSubview:bgImage];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
}

/**
 @brief 初始化侧滑控制器
 @param leftVC 左视图控制器
 mainVC 中间视图控制器
 @result instancetype 初始化生成的对象
 */
- (instancetype)initWithLeftView:(UIViewController *)leftVC
                     andMainView:(UIViewController *)mainVC
{
    if(self = [super init]){
        self.speedf = vSpeedFloat;
        
        self.leftVC = leftVC;
        self.mainVC = mainVC;
        
        // 将左视图添加到该视图控制器的视图上
        [self.view addSubview:self.leftVC.view];
        
        // 设置左视图控制器上的tableView
        // 获取左侧tableview
        for (UIView *obj in self.leftVC.view.subviews) {
            if ([obj isKindOfClass:[UITableView class]]) {
                self.leftTableview = (UITableView *)obj;
            }
        }
        // 设置背景
        self.leftTableview.backgroundColor = [UIColor clearColor];
        self.leftTableview.alpha = 0.6;
        //设置左侧tableview的初始位置和缩放系数
        self.leftTableview.frame = CGRectMake(0, 0, kScreenWidth - kMainPageDistance, kScreenHeight);
        self.leftTableview.center = CGPointMake(kLeftCenterX, kScreenHeight * 0.5);
        
        self.leftTableview.transform = CGAffineTransformMakeScale(kLeftScale, kLeftScale);
        
        //蒙版
        self.contentView = [[UIView alloc] init];
        self.contentView.frame = self.leftVC.view.bounds;
        self.contentView.backgroundColor = [UIColor blackColor];
        self.contentView.alpha = 0.5;
        [self.leftVC.view addSubview:self.contentView];
        
        // 为主视图设置手势
        // 创建滑动手势对象
        self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
        // 为手势对象设置代理
        self.pan.delegate = self;
        // 将滑动手势对象添加到主视图控制器的视图手势上
        [self.mainVC.view addGestureRecognizer:self.pan];
        // 将主视图添加到self.view 上
        [self.view addSubview:self.mainVC.view];
        
        self.closed = YES;//初始时侧滑窗关闭
        
    }
    return self;
}

#pragma mark - 滑动手势

//滑动手势
- (void) handlePan: (UIPanGestureRecognizer *)rec{
    // 实时手势位置
    CGPoint point = [rec translationInView:self.view];
    // 实时位移大小
    _scalef = (point.x * self.speedf + _scalef);
    
    BOOL needMoveWithTap = YES;  //是否还需要跟随手指移动
    // 判断是不是有效滑动
    if (((CGRectGetMinX(self.mainVC.view.frame) <= 0) && (_scalef <= 0)) || ((CGRectGetMinX(self.mainVC.view.frame) >= (kScreenWidth - kMainPageDistance )) && (_scalef >= 0)))
    {
        //边界值管控
        _scalef = 0;
        // 无效滑动时 视图的位置不在变动
        needMoveWithTap = NO;
    }
    
    // 根据视图位置判断是左滑还是右边滑动
    if (needMoveWithTap && (rec.view.frame.origin.x >= 0) && (rec.view.frame.origin.x <= (kScreenWidth - kMainPageDistance)))
    {
        CGFloat recCenterX = rec.view.center.x + point.x * self.speedf;
        if (recCenterX < kScreenWidth * 0.5) {
            recCenterX = kScreenWidth * 0.5;
        }
        
        // 对主视图做相应的更改
        CGFloat recCenterY = rec.view.center.y;
        // 设置中心点位置（即改变其原有位置）
        rec.view.center = CGPointMake(recCenterX,recCenterY);
        
        //scale 1.0~kMainPageScale
        CGFloat scale = 1 - (1 - kMainPageScale) * (rec.view.frame.origin.x / (kScreenWidth - kMainPageDistance));
        // 设置形变
        // CGAffineTransformIdentity属性能还原到 进行动画 之前的状态
        rec.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,scale, scale);
        
        // 对左视图做相应的修改
        // 修改位置，设置形变
        CGFloat leftTabCenterX = kLeftCenterX + ((kScreenWidth - kMainPageDistance) * 0.5 - kLeftCenterX) * (rec.view.frame.origin.x / (kScreenWidth - kMainPageDistance));
        //leftScale kLeftScale~1.0
        CGFloat leftScale = kLeftScale + (1 - kLeftScale) * (rec.view.frame.origin.x / (kScreenWidth - kMainPageDistance));
        
        self.leftTableview.center = CGPointMake(leftTabCenterX, kScreenHeight * 0.5);
        self.leftTableview.transform = CGAffineTransformScale(CGAffineTransformIdentity, leftScale,leftScale);
        
        //tempAlpha kLeftAlpha~0
        // 设置蒙版的透明度
        CGFloat tempAlpha = kLeftAlpha - kLeftAlpha * (rec.view.frame.origin.x / (kScreenWidth - kMainPageDistance));
        self.contentView.alpha = tempAlpha;
        
        // 重置点（为了使每次触发都当做首次触发）
        [rec setTranslation:CGPointMake(0, 0) inView:self.view];
        
        
    }
    else
    {
        //超出范围，
        if (CGRectGetMinX(self.mainVC.view.frame)< 0)
        {
            [self closeLeftView];
            _scalef = 0;
        }
        else if (CGRectGetMinX(self.mainVC.view.frame) > (kScreenWidth - kMainPageDistance))
        {
            [self openLeftView];
            _scalef = 0;
        }
    }
    
    //手势结束后修正位置,超过约一半时向多出的一半偏移
    if (rec.state == UIGestureRecognizerStateEnded) {
        if (fabs(_scalef) > vCouldChangeDeckStateDistance)
        {
            if (self.closed)
            {
                [self openLeftView];
            }
            else
            {
                [self closeLeftView];
            }
        }
        else
        {
            if (self.closed)
            {
                [self closeLeftView];
            }
            else
            {
                [self openLeftView];
            }
        }
        _scalef = 0;
    }
}


#pragma mark - 单击手势
-(void)handeTap:(UITapGestureRecognizer *)tap{
    
    if ((!self.closed) && (tap.state == UIGestureRecognizerStateEnded))
    {
        [UIView beginAnimations:nil context:nil];
        
        // 将主视图缩放到原形
        tap.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
        // 重新确定主视图的位置
        tap.view.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2,[UIScreen mainScreen].bounds.size.height/2);
        
        // 设定左视图为关闭状态
        self.closed = YES;
        
        // 设置左视图上的tableView的位置和缩放
        self.leftTableview.center = CGPointMake(kLeftCenterX, kScreenHeight * 0.5);
        self.leftTableview.transform = CGAffineTransformScale(CGAffineTransformIdentity,kLeftScale,kLeftScale);
        self.contentView.alpha = kLeftAlpha;
        
        [UIView commitAnimations];
        _scalef = 0;
        [self removeSingleTap];
    }
    
}

#pragma mark - 修改视图位置
/**
 @brief 关闭左视图
 */
- (void)closeLeftView
{
    [UIView beginAnimations:nil context:nil];
    
    // 将主视图缩放到原形
    self.mainVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
    // 重新确定主视图的位置
    self.mainVC.view.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
    // 设定左视图为关闭状态
    self.closed = YES;
    
    // 设置左视图上的tableView的位置和缩放
    self.leftTableview.center = CGPointMake(kLeftCenterX, kScreenHeight * 0.5);
    self.leftTableview.transform = CGAffineTransformScale(CGAffineTransformIdentity,kLeftScale,kLeftScale);
    
    // 设置蒙版的透明度
    self.contentView.alpha = kLeftAlpha;
    
    [UIView commitAnimations];
    [self removeSingleTap];
}

/**
 @brief 打开左视图
 */
- (void)openLeftView;
{
    [UIView beginAnimations:nil context:nil];
    // 打开左视图 主视图将缩放到事先确定好的比例 并且放置到 事先确定好的位置
    self.mainVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,kMainPageScale,kMainPageScale);
    self.mainVC.view.center = kMainPageCenter;
    // 设定左视图为打开状态
    self.closed = NO;
    
    // 设置左视图上的tableView的位置和缩放
    self.leftTableview.center = CGPointMake((kScreenWidth - kMainPageDistance) * 0.5, kScreenHeight * 0.5);
    self.leftTableview.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
    // 设置蒙版的透明度
    self.contentView.alpha = 0;
    
    [UIView commitAnimations];
    [self disableTapButton];
}

#pragma mark - 行为控制
// 设置单机手势
- (void)disableTapButton
{
//    for (UIButton *tempButton in [_mainVC.view subviews])
//    {
//        [tempButton setUserInteractionEnabled:NO];
//    }
    //单击
    if (!self.sideslipTapGes)
    {
        // 创建单击手势对象
        self.sideslipTapGes= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap:)];
        // 设置单机次数
        [self.sideslipTapGes setNumberOfTapsRequired:1];
        
        // 将单机手势添加到mainVC.view上
        [self.mainVC.view addGestureRecognizer:self.sideslipTapGes];
        //        self.sideslipTapGes.cancelsTouchesInView = YES;  //点击事件盖住其它响应事件,但盖不住Button;
    }
}

//关闭点击行为
- (void) removeSingleTap
{
//    for (UIButton *tempButton in [self.mainVC.view  subviews])
//    {
//        [tempButton setUserInteractionEnabled:YES];
//    }
    [self.mainVC.view removeGestureRecognizer:self.sideslipTapGes];
    self.sideslipTapGes = nil;
}

/**
 *  设置滑动开关是否开启
 *
 *  @param enabled YES:支持滑动手势，NO:不支持滑动手势
 */

- (void)setPanEnabled: (BOOL) enabled
{
    [self.pan setEnabled:enabled];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    
    if(touch.view.tag == vDeckCanNotPanViewTag)
    {
        //        NSLog(@"不响应侧滑");
        return NO;
    }
    else
    {
        //        NSLog(@"响应侧滑");
        return YES;
    }
}

@end
